package cn.liu.jetpack_demo.utils

import okhttp3.Interceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okio.Buffer
import java.io.IOException
import java.util.concurrent.TimeUnit
import cn.liu.jetpack_demo.api.IPassportApi

object HttpUtil {

    private const val BASE_URL = "http://192.168.2.104:10089/" // 替换为你的API地址

    private val client = OkHttpClient.Builder()
        .readTimeout(60, TimeUnit.SECONDS)
        .writeTimeout(60, TimeUnit.SECONDS)
        .connectTimeout(60, TimeUnit.SECONDS)
//        .addInterceptor(BaseRequestInterceptor())
        .build()

    private val retrofit: Retrofit by lazy {
        Retrofit.Builder()
            .baseUrl(BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .client(client)
            .build()
    }

//    val passportApi: IPassportApi by lazy {
//        retrofit.create(IPassportApi::class.java)
//    }

    fun <T> createService(serviceClass: Class<T>): T {
        return retrofit.create(serviceClass)
    }
}

class BaseRequestInterceptor : Interceptor {

    @Throws(IOException::class)
    override fun intercept(chain: Interceptor.Chain): Response {
        val originalRequest = chain.request()

        // 拦截请求前的操作，例如修改请求体或添加通用参数
        val requestBuilder = originalRequest.newBuilder()
            .addHeader("X-My-Header", "Value")

        // 如果需要对POST请求的FormBody或者JSON Body进行修改，可以在这里读取并修改
        val requestBody = originalRequest.body

        // 假设我们要对POST请求的body内容进行统一处理
        if (requestBody != null && originalRequest.method == "POST" || originalRequest.method == "PUT") {
            val requestBody = originalRequest.body ?: return chain.proceed(originalRequest)

            // 获取原始请求体的内容
            val buffer = Buffer()
            requestBody.writeTo(buffer)
            val bodyString = buffer.readUtf8()

            // 这里仅做演示，实际根据需求修改请求体
            val modifiedBody = modifyRequestBody(bodyString) // 自定义修改请求体的方法

            // 重新构建请求体
            val newRequestBody = modifiedBody.toRequestBody(requestBody.contentType())
            requestBuilder.method(originalRequest.method, newRequestBody)
        }

        // 创建新的请求
        val newRequest = requestBuilder.build()

        // 继续执行网络请求
        return chain.proceed(newRequest)
    }

    // 示例方法，根据实际情况实现
    private fun modifyRequestBody(body: String): String {
        // 在这里对请求体进行修改，比如添加公共参数、加密等操作
        // 返回修改后的字符串
        return body + "\n附加信息"
    }
}

